//
//  ComposeViewController.swift
//  SinaWeibo
//
//  Created by yang on 15/11/19.
//  Copyright © 2015年 yang. All rights reserved.
//

import UIKit
import SVProgressHUD
class ComposeViewController: UIViewController {
    var index:Bool = true
    //懒加载表情键盘
    private lazy var keyBoardView : EmoticonKeyBoardView = EmoticonKeyBoardView { (emoticon) -> () in
         self.textView.insertAttrText(emoticon)
    }
    //点击表情
    @objc private func selectEmoticon(){
        textView.resignFirstResponder()
        textView.inputView = (textView.inputView == nil ? keyBoardView : nil)
        textView.becomeFirstResponder()
    }
    //点击图片
    @objc private  func selectPicture(){
        if index == true {
            textView.resignFirstResponder()
            selectorVC.view.snp_updateConstraints { (make) -> Void in
                make.height.equalTo(224 + 80 + 40)
            }
            index = false
        }else {
            textView.becomeFirstResponder()
            selectorVC.view.snp_updateConstraints { (make) -> Void in
                make.left.right.bottom.equalTo(view)
                make.height.equalTo(0)
            }
            index = true
                    }
    }
    //关闭发布微博页面
    @objc private  func close(){
     dismissViewControllerAnimated(true , completion: nil)
    }
    //发布微博
    @objc private  func send(){
        guard let tooken = UserAccountViewModel().tooken  else {
        SVProgressHUD.showErrorWithStatus("你还没有登录")
        return
        }
        let parameters = ["access_token":tooken,"status":textView.fulltext()]
        if selectorVC.imageList.count >= 1{
            let urlString = "https://upload.api.weibo.com/2/statuses/upload.json"
            let data = UIImagePNGRepresentation(selectorVC.imageList[0])
            NetworkTools.sharedTools.uplaodImage(urlString, parameters: parameters, imageData: data!, finished: { (reulst, error) -> () in
                if error != nil{
                SVProgressHUD.showErrorWithStatus("你还没有登录")
                return
                }
               SVProgressHUD.showSuccessWithStatus("发送成功")
               self.dismissViewControllerAnimated(true , completion: nil)
            })
        }else{
            let url = "2/statuses/update.json"
            NetworkTools.sharedTools.requestJsonDict(.POST, urlString: url, parameters: parameters) { (dict, error) -> () in
                if error != nil{
                    SVProgressHUD.showErrorWithStatus(AppErrorTip)
                    return
                }
                SVProgressHUD.showSuccessWithStatus("发送成功")
                self.dismissViewControllerAnimated(true , completion: nil)
            }
        }
   }
    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = UIColor.whiteColor()
        setNavbar()
        setupTextView()
        setupToolBar()
        setSelectorView()
        registerNotification()
    }
    //键盘监听
    private func registerNotification(){
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillChange:", name: UIKeyboardWillChangeFrameNotification, object: nil)
    }
    @objc private func keyboardWillChange(notify:NSNotification){
        selectorVC.view.snp_updateConstraints { (make) -> Void in
            make.left.right.bottom.equalTo(view)
            make.height.equalTo(0)
        }
        //键盘动画时间
        let duration = notify.userInfo![UIKeyboardAnimationDurationUserInfoKey] as! Double
        //键盘移动结束后的位置
        let rect =  (notify.userInfo![UIKeyboardFrameEndUserInfoKey] as! NSValue).CGRectValue()
        let a = notify.userInfo![UIKeyboardAnimationCurveUserInfoKey] as! Int
        //toolBar 的偏移量 = - 键盘高度
        let offset = -screenH + rect.origin.y
        toolBar.snp_updateConstraints { (make) -> Void in
            make.bottom.equalTo(offset)
        }
        UIView.animateWithDuration(duration) { () -> Void in
            UIView.setAnimationCurve(UIViewAnimationCurve(rawValue: a)!)
            self.view.layoutIfNeeded()
        }
    }
    deinit {
    NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    private lazy var textView : EmoticonTextView = {
       let t = EmoticonTextView()
        t.delegate = self
        t.font = UIFont.systemFontOfSize(18)
        t.textColor = UIColor.darkGrayColor()
        t.keyboardDismissMode = UIScrollViewKeyboardDismissMode.OnDrag
        t.alwaysBounceVertical = true
       return t
    }()
    private lazy var placeHolderLabel :UILabel = UILabel(title: "分享新鲜事...", size: 18, color: UIColor.lightGrayColor())
    private lazy var toolBar:UIToolbar = UIToolbar()
    private lazy var selectorVC:PictureSelectorViewController = PictureSelectorViewController()
    
}
extension ComposeViewController{
    //添加导航条
    private func setNavbar(){
        self.navigationItem.leftBarButtonItem = UIBarButtonItem(title: "返回", style: .Plain, target: self, action: "close")
        self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "发布", style: .Plain, target: self, action: "send")
        self.navigationItem.rightBarButtonItem?.enabled = false
        let titleView = UIView(frame: CGRect(x: 0, y: 0, width: 200, height: 40))
        navigationItem.titleView = titleView
        let titleLabel = UILabel(title: "发微博", size: 17, color: UIColor.darkGrayColor())
        let nameLabel = UILabel(title: UserAccountViewModel().userName ?? "", size: 14, color: UIColor.lightGrayColor())
        titleView.addSubview(titleLabel)
        titleView.addSubview(nameLabel)
        titleLabel.snp_makeConstraints { (make) -> Void in
            make.top.centerX.equalTo(titleView)
        }
        nameLabel.snp_makeConstraints { (make) -> Void in
            make.bottom.centerX.equalTo(titleView)
        }
    }
    //文本输入框
    private func setupTextView(){
        view.addSubview(textView)
        textView.addSubview(placeHolderLabel)
        textView.snp_makeConstraints { (make) -> Void in
            make.top.left.right.equalTo(view)
            make.height.equalTo(view.bounds.height / 3)
        }
        placeHolderLabel.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(textView).offset(8)
            make.left.equalTo(textView).offset(5)
        }
    }
    //设置底部的工具栏
    private func setupToolBar(){
        view.addSubview(toolBar)
        toolBar.snp_makeConstraints { (make) -> Void in
            make.left.right.bottom.equalTo(view)
            make.height.equalTo(40)
        }
        var items = [UIBarButtonItem]()
        let itemSettings = [["imageName": "compose_toolbar_picture","actionName": "selectPicture"],
            ["imageName": "compose_mentionbutton_background"],
            ["imageName": "compose_trendbutton_background"],
            ["imageName": "compose_emoticonbutton_background","actionName":"selectEmoticon"],
            ["imageName": "compose_add_background"]]
        for dict in itemSettings {
            let item = UIBarButtonItem(imageName: dict["imageName"]!, target: self, actionName: dict["actionName"])
            items.append(item)
            let space = UIBarButtonItem(barButtonSystemItem: .FlexibleSpace, target: nil, action: nil)
            items.append(space)
        }
        items.removeLast()
        toolBar.items = items
    }
    //图片选择器
    private func setSelectorView(){
        addChildViewController(selectorVC)
        view.addSubview(selectorVC.view)
        view.bringSubviewToFront(toolBar)
        selectorVC.view.snp_makeConstraints { (make) -> Void in
            make.left.right.bottom.equalTo(view)
            make.height.equalTo(0)
        }
    }
}
//UITextView 的代理
extension ComposeViewController:UITextViewDelegate{
    func textViewDidChangeSelection(textView: UITextView) {
        placeHolderLabel.hidden = textView.hasText()
        self.navigationItem.rightBarButtonItem?.enabled = textView.hasText()
    }
}